﻿using BeetleX.XRPC.HostedServices;
using EventNext;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace BeetleX.XRPC.Extensions;

public static class XRPCExtension
{
    public static IServiceCollection UseXRPC(this IServiceCollection service, Action<XRPCServer> action, Action<XRPCServer> startCallback = null, Assembly[] assemblies = null)
    {
        service.AddSingleton<HttpSettingHandler>(new HttpSettingHandler()
        {
            Assemblies = assemblies,
            Options = action,
            Services = service,
            StartCallBack = startCallback
        });
        if (assemblies?.Length > 0)
        {
            for (int i = 0; i < assemblies.Length; i++)
            {
                Type[] types = assemblies[i].GetTypes();
                foreach (Type type in types)
                {
                    if (type.GetCustomAttribute<ServiceAttribute>(false) != null)
                    {
                        service.AddTransient(type);
                    }
                }
            }
        }
        return service.AddHostedService<XRPCServerHosting>();
    }

    public static IServiceProvider ServiceProvider(this XRPCServer server)
    {
        return (IServiceProvider)server["__ServiceProvider"];
    }
}